package com.spark.common.widget

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.text.InputType
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.*
import com.spark.common.R
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick

class RichView : LinearLayout {
    private lateinit var image: ImageView
    private lateinit var text: TextView

    constructor(context: Context?) : super(context)

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun getRootView(): View {
        return AnkoContext.createDelegate(this).apply {
            gravity = Gravity.CENTER
            padding = dip(24)
            image = imageView(imageResource = R.drawable.ic_arrow_down) {
                onClick { startAnimate() }
                padding = dip(8)
                layoutParams = LinearLayout.LayoutParams(dip(48), dip(48))
            }
            text = textView("Anko Rich View") {
                textSize = 19F
            }
        }.view
    }

    private fun startAnimate() {
        if (image.animation != null) return
        image.startAnimation(ScaleAnimation(1f, 1.3f, 1f, 1.3f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f).apply {
            repeatCount = 1
            repeatMode = Animation.REVERSE
            duration = 1000
        })
    }
}

class SimpleUi : AnkoComponent<AppCompatActivity> {
    private val style = { v: Any ->
        when (v) {
            is Button -> v.textSize = 26f
            is EditText -> v.textSize = 24f
        }
    }

    override fun createView(ui: AnkoContext<AppCompatActivity>) = with(ui) {
        verticalLayout {
            padding = dip(32)
            imageView(imageResource = R.drawable.ic_arrow_down).lparams {
                margin = dip(6)
                gravity = Gravity.CENTER
            }
            val name = editText {
                hint = "hint"
                background = null
            }
            val password = editText {
                hint = "password"
                inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_NUMBER_VARIATION_PASSWORD
                background = null
            }
            button("login") {
                onClick {
                }
                allCaps = false
            }
        }.applyRecursively(style)
    }

}